package cn.loyle.utils;

import act.app.ActionContext;
import com.sun.org.apache.regexp.internal.RE;
import com.xiaoleilu.hutool.crypto.digest.DigestAlgorithm;
import com.xiaoleilu.hutool.crypto.digest.Digester;
import com.xiaoleilu.hutool.date.DateUnit;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.json.JSON;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.setting.Setting;
import com.xiaoleilu.hutool.util.StrUtil;
import org.nutz.json.Json;
import org.osgl.http.H;
import org.osgl.util.Str;

import java.io.File;
import java.util.Arrays;

public class WxUtil {

    public static Setting setting = new Setting("wx.setting");

    /**
     * 校验微信token
     * @param context
     * @param token
     * @return
     */
    public static boolean checkIsWx(ActionContext context, String token){
        H.Request req = context.req();
        String signature = req.paramVal("signature");
        if (signature != null) {
            String timestamp = req.paramVal("timestamp");
            String nonce = req.paramVal("nonce");
            String[] parms = new String[]{token, timestamp, nonce};
            Arrays.sort(parms);
            String parmsString = "";
            for (int i = 0; i < parms.length; i++) {
                parmsString += parms[i];
            }
            String mParms = new Digester(DigestAlgorithm.SHA1).digestHex(parmsString);
            return mParms.equals(signature);
        }else {
            return false;
        }
    }

    /**
     * 获取access_token并存储到本地文件中，超过两个小时则重新获取
     * @return
     */
    public static String getAccessToken() {
        File file = FileUtil.file("access_token.txt");
        JSONObject jsonObject = null;
        String s = "";
        if (file.exists()){
             s = FileUtil.readUtf8String(file);
        }
        if (s!=""&&DateUtil.between(DateUtil.date(new JSONObject(s).getLong("time")),DateUtil.date(), DateUnit.HOUR)<2){
            return new JSONObject(s).getStr("access_token");
        } else {
            jsonObject = new JSONObject();
            String APPID = setting.getStr("appid");
            String SECERT = setting.getStr("secret");
            String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECERT, (String) null);
            String token = new JSONObject(post).getStr("access_token");
            jsonObject.put("access_token",token);
            jsonObject.put("time", DateUtil.current(false));
            FileUtil.writeUtf8String(JSONUtil.toJsonStr(jsonObject),file);
            FileUtil.touch(file);
            return token;
        }
    }

    /**
     * 发送模板消息，template_id要是自己的模板ID
     * templetText中为根据模板写的jsonStr
     * @param touser
     * @param title
     * @param content
     * @return
     */
    public static String sendWithTemplet(String touser,String title,String content){
        String templetText = "{" +
                "     \"touser\":\""+touser+"\", " +
                "     \"template_id\":\"8xoDUJfx2dWjqSyfTd-IOekeD1d_wYL1OWOx5cZAycU\", " +
                "     \"data\":{ " +
                "             \"title\": { " +
                "                 \"value\":\""+title+"\"" +
                "             }, " +
                "             \"first\": { " +
                "                 \"value\":\""+content+"\"" +
                "             }" +
                "     } " +
                " }  ";
        String access_token = WxUtil.getAccessToken();
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token,templetText);
        return post;
    }
}
